var express = require('express');
let multiparty = require("multiparty");
let path = require("path");
const { post, route } = require('.');
var router = express.Router();
let jwt = require('./jwt.js');

const userService = require('../service/userService')

//注册
router.post('/reg', async function (req, res) {
  let { username, password, telephone, email, createTime,privilege } = req.body;//获取数据
  let data = await userService.insert({ username, password, telephone, email, createTime,privilege });//这里用的解构方法，属性名：属性值，用语法糖简写
  res.send(data);
});

//判断用户名是否存在
router.post('/usernameExist', async function (req, res) {
  let { username } = req.body;
  let data = await userService.findByUsername(username);
  console.log("111",data);
  if (data.length > 0) {//如果用户名的长度大于0则代表用户名已经存在了
    res.send({ status: 0 });
  } else {//如果用户没有重复则注册
    res.send({ status: 1 });
  }
});


//登录
router.post('/login', async function (req, res) {
  let { username, password } = req.body;
  let data = await userService.findByUsernameAndPassword({ username, password });
  console.log(data);
  if (data) {
    /*
    注意：无论是使用cookie，session还是jwt
    我们都是通过响应头传送的这些信息
    服务器端有数据返回到客户端时，使用res.send();
    意思是：传送反馈信息的同时，响应头传送了cookie,session 或者 jwt
    */
    //登录之后，调用publishToken()函数生成token
    let token = jwt.publishToken(res, { username, password });
    console.log(token);
    // req.session.user = data[0]; //是一个用户对象 data是一个数组，data[0]就是数组里面的每一个对象{id:,username:,password:}
    res.send({ code: 0, msg: "登录成功", data });
  } else {
    res.send({ code: -1, msg: "登录失败", data: null });
  }
  // res.send(data);
});
//验证token是否和数据库匹配
router.get("/verify/whoami", async (req, res) => {
  // let token = "";

  // if (req.cookies.token) {
  //   token = req.cookies.token
  // }
  // else {
  //   token = req.session.loginUser._id;
  //   console.log(token);
  // }

  // let result = await userService.findUser(token);

  let result = jwt.verifyToken(req); //得到客户端请求时携带的token

  if (!result) {
    res.send({ code: -1, msg: "用户名或密码不正确", data: null });
  } else {
    res.send({ code: 0, msg: "验证成功", data: result });
  }
});
//新增
router.post('/', async function (req, res) {
  let { username, password, telephone, email, privilege, picture } = req.body;//获取数据
  console.log(username, password, telephone, email, privilege,picture);
  let data = await userService.insert({ username, password, telephone, email, privilege,picture});
  // let { username, password, telephone, email, createTime,picture } = req.body;//获取数据
  // let data = await userService.insert({ username, password, telephone, email, createTime,picture});
  res.send(data);
});

//查询所有
router.get('/', async function (req, res) {
  let { type, value, current, pageSize } = req.query;
  let searchParams = {};
  searchParams[type] = new RegExp(value); //模糊查询
  let data = await userService.find({ current: current || 1, pageSize: pageSize || 5 }, searchParams);
  res.send(data);
});

//按id查询
router.get('/:id', async function (req, res) {
  let { id } = req.params;//获取路径后面的变量用params
  let data = await userService.findById(id);
  res.send(data);
});

//删除
router.delete('/:id', async function (req, res) {
  let { id } = req.params;
  let data = await userService.delete(id);
  console.log("delete",data);
  res.send(data);
});

//修改
router.put('/:id', async function (req, res) {
  let { id } = req.params;
  let { username, password, telephone, email, picture,privilege } = req.body;
  let data = await userService.update({ _id: id, username, password, telephone, email, picture,privilege });
  res.send(data);
});

//上传图片
router.post("/upload", function (req, res) {
  let imgPath = path.join(__dirname, "../public/images"); //后端图片保存路径 

  var form = new multiparty.Form({ uploadDir: imgPath }); //图片上传到哪里去
  form.parse(req, function (err, fields, files) {
    /*
        console.log(fields.username[0])
        console.log(fields.password[0])

        Object.keys(fields).forEach(function(name) {
            console.log('got field named ' + name + "--" + fields[name] + "----" + typeof fields[name]);
        });

        Object.keys(files).forEach(function(name) {
            console.log(files[name]);
        });
    */

    if (err) {
      res.send({ code: 1, msg: "上传失败", data: err });
    } else {
      var p = files.file[0].path.substring(
        files.file[0].path.indexOf("images")
      );
      console.log(p);
      res.send({ code: 0, msg: "上传成功", data: path.basename(p) }); //上传图片成功以后，返回图片名字
    }
  });
});

module.exports = router;
